package net.hn.hnms.biz.gasext.dws.service.impl;


import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import net.hn.hnms.biz.api.mine.RemoteMineInfoService;
import net.hn.hnms.biz.api.safety.gasext.domain.MinePointInAlarmfoVo;
import net.hn.hnms.biz.api.safety.gasext.domain.SafetyMonitoringVo;
import net.hn.hnms.biz.api.safety.gasext.domain.TransfiniteStatisticsVo;
import net.hn.hnms.biz.api.safety.location.model.OutLimitAlarmingInfoVO;
import net.hn.hnms.biz.gasext.dws.domain.AqjcYcbjPo;
import net.hn.hnms.biz.gasext.dws.domain.DimCoalMineBasicInfoPo;
import net.hn.hnms.biz.gasext.dws.domain.DwsAqjcYcbjDFPo;
import net.hn.hnms.biz.gasext.dws.mapper.AqjcCdssMapper;
import net.hn.hnms.biz.gasext.dws.mapper.AqjcYcbjMapper;
import net.hn.hnms.biz.gasext.dws.mapper.DimCoalMineBasicInfoMapper;
import net.hn.hnms.biz.gasext.dws.mapper.SysOrganizationDwsMapper;
import net.hn.hnms.biz.gasext.dws.service.AqjkService;
import net.hn.hnms.biz.gasext.dws.service.DwsService;
import net.hn.hnms.sys.common.core.utils.DateUtils;
import net.hn.hnms.sys.common.core.utils.StringUtils;
import net.hn.hnms.sys.common.redis.domain.SysOrganization;
import net.hn.hnms.sys.common.redis.domain.SysOrganizationVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

@Service
@DS(value = "dwsMonitor")
public class AqjkServiceImpl implements AqjkService {


    @Resource
    private AqjcCdssMapper aqjcCdssMapper;

    @Resource
    private AqjcYcbjMapper aqjcYcbjMapper;
    @Resource
    private RemoteMineInfoService remoteMineInfoService;


    @Resource
    private SysOrganizationDwsMapper sysOrganizationMapper;

    /**
     * 煤矿信息表
     */
    @Resource
    private DimCoalMineBasicInfoMapper dimCoalMineBasicInfoMapper;

    @Resource
    private DwsService dwsService;
    /**
     * 大屏首页-安全检测（本地数据）
     * @return
     */
    @Override
    public SafetyMonitoringVo getSafetyMonitoringLocl() {
        SafetyMonitoringVo safetyMonitoringVo = new SafetyMonitoringVo();
        //煤矿列表集合
        List<MinePointInAlarmfoVo> minePointInAlarmfoVoList = new ArrayList<>();
        //获取所有煤矿
        List<SysOrganization> list = this.selectCodeSubMineList();

        //去除露天矿
        //魏家峁 150622B0012000210118
        // 铧尖  未知
        // 伊敏  150724B0012000510053
        //20240809 去除 刘园子：621022009406  和  马蹄沟：620824009852
        List<String> codesToRemove = Arrays.asList("150622B0012000210118", "150724B0012000510053","621022009406","620824009852");
        list = list.stream()
                .filter(dto -> !codesToRemove.contains(dto.getOrgCode()))
                .collect(Collectors.toList());



        Integer ch4Number = 0;
        Integer coNumber= 0;

        for (SysOrganization sysOrganization : list) {
            //查询当前煤矿的所有测点 实时表
            Integer pointNumber = aqjcCdssMapper.selectPointNumber(sysOrganization.getOrgCode());
            //一氧化碳报警
            Integer coWarnCount = aqjcCdssMapper.selectCoWarnCount(sysOrganization.getOrgCode());
            //甲烷报警
            Integer ch4WarnCount = aqjcCdssMapper.selectCH4WarnCount(sysOrganization.getOrgCode());
            MinePointInAlarmfoVo minePointInAlarmfoVo = new MinePointInAlarmfoVo();
            minePointInAlarmfoVo.setMineCode(sysOrganization.getOrgCode());
            minePointInAlarmfoVo.setMineName(sysOrganization.getOrgName());
            minePointInAlarmfoVo.setPointNumber(pointNumber);
            minePointInAlarmfoVo.setCoWarnCount(coWarnCount);
            minePointInAlarmfoVo.setCH4WarnCount(ch4WarnCount);
            minePointInAlarmfoVoList.add(minePointInAlarmfoVo);


            //甲烷测点数
            ch4Number+=ch4Number = aqjcCdssMapper.selectCH4NumberAll(sysOrganization.getOrgCode());
            //一氧化碳测点数
            coNumber+=coNumber = aqjcCdssMapper.selectCONumberAll(sysOrganization.getOrgCode());
        }

        //计算测点总数
        int pointNumberSum = minePointInAlarmfoVoList.stream()
                .mapToInt(MinePointInAlarmfoVo::getPointNumber)
                .sum();

        //计算CH4超限数
        int cH4WarnCountSum = minePointInAlarmfoVoList.stream()
                .mapToInt(MinePointInAlarmfoVo::getCH4WarnCount)
                .sum();
        //计算CO超限数
        int coWarnCountSum = minePointInAlarmfoVoList.stream()
                .mapToInt(MinePointInAlarmfoVo::getCoWarnCount)
                .sum();



        safetyMonitoringVo.setMinePointInAlarmfoList(minePointInAlarmfoVoList);
        safetyMonitoringVo.setPonitSum(pointNumberSum);
        safetyMonitoringVo.setCH4WarnCount(cH4WarnCountSum);
        safetyMonitoringVo.setCoWarnCount(coWarnCountSum);
        safetyMonitoringVo.setCH4Number(ch4Number);
        safetyMonitoringVo.setCoNumber(coNumber);

        return safetyMonitoringVo;
    }


    //获取编码列表及子列表
    @Override
    public SysOrganizationVo selectCodeSubList() {
        //获取一级编码（集团级）
        SysOrganization organizations1 = sysOrganizationMapper.selectOne(new LambdaQueryWrapper<SysOrganization>().eq(SysOrganization::getOrgCode, "0"));

        SysOrganizationVo sysOrganizationVo = new SysOrganizationVo();
        sysOrganizationVo.setOrgName(organizations1.getOrgName().trim());
        sysOrganizationVo.setOrgCode(organizations1.getOrgCode());
        sysOrganizationVo.setParentCode(null);
        //获取二级编码（公司级）
        List<SysOrganization> organizations2 = sysOrganizationMapper.selectList(new LambdaQueryWrapper<SysOrganization>().eq(SysOrganization::getParentCode, organizations1.getOrgCode()));
        //二级编码封装
        List<SysOrganizationVo> organizationVoList2 = organizations2.stream().map(t -> {
            SysOrganizationVo sysOrganizationVo2 = new SysOrganizationVo();
            sysOrganizationVo2.setOrgName(t.getOrgName().trim());
            sysOrganizationVo2.setOrgCode(t.getOrgCode());
            sysOrganizationVo2.setParentCode(t.getParentCode());

            //获取三级编码（煤矿级）
            List<SysOrganization> organizations3 = sysOrganizationMapper.selectList(new LambdaQueryWrapper<SysOrganization>().eq(SysOrganization::getParentCode, t.getOrgCode()));
            //三级编码封装
            List<SysOrganizationVo> sysOrganizationVoList3 = organizations3.stream().map(m -> {
                SysOrganizationVo sysOrganizationVo3 = new SysOrganizationVo();
                sysOrganizationVo3.setOrgName(m.getOrgName().trim());
                sysOrganizationVo3.setOrgCode(m.getOrgCode());
                sysOrganizationVo3.setParentCode(m.getParentCode());
                return sysOrganizationVo3;
            }).collect(Collectors.toList());
            sysOrganizationVo2.setSubCodeList(sysOrganizationVoList3);
            return sysOrganizationVo2;
        }).collect(Collectors.toList());
        sysOrganizationVo.setSubCodeList(organizationVoList2);
        return sysOrganizationVo;
    }

    /**
     *   获取华能所有子煤矿
     * @return
     */
    @Override
    public List<SysOrganization> selectCodeSubMineList() {
//        List<SysOrganization> list = new ArrayList<>();
//        SysOrganizationVo sysOrganizationVo = this.selectCodeSubList();
//        //二级
//        List<SysOrganizationVo> subCodeList = sysOrganizationVo.getSubCodeList();
//        for (SysOrganizationVo organizationVo : subCodeList) {
//            //三级
//            for (SysOrganizationVo vo : organizationVo.getSubCodeList()) {
//                SysOrganization sysOrganization = new SysOrganization();
//                sysOrganization.setOrgCode(vo.getOrgCode());
//                sysOrganization.setOrgName(vo.getOrgName());
//                list.add(sysOrganization);
//            }
//        }
        //获取dim模式里煤矿信息
        List<DimCoalMineBasicInfoPo> dimCoalMineBasicInfoPos = dimCoalMineBasicInfoMapper.selectList(null);

        // 过滤掉煤矿编码为空的记录
         dimCoalMineBasicInfoPos = dimCoalMineBasicInfoPos.stream()
                .filter(t -> t.getMkCode() != null && !t.getMkCode().isEmpty())
                .collect(Collectors.toList());

         //去掉马蹄沟（620824009852）和刘园子煤矿（621022009406）
        List<String> codesToRemove = Arrays.asList("620824009852", "621022009406");
        dimCoalMineBasicInfoPos = dimCoalMineBasicInfoPos.stream()
                .filter(t -> !codesToRemove.contains(t.getMkCode()))
                .collect(Collectors.toList());




        // 按照 mkRank 排序
        List<DimCoalMineBasicInfoPo> sortedList = dimCoalMineBasicInfoPos.stream()
                .sorted(Comparator.nullsLast(Comparator.comparing(DimCoalMineBasicInfoPo::getMkRank)))
                .collect(Collectors.toList());

        List<SysOrganization> collect = sortedList.stream().map(t -> {
            SysOrganization sysOrganization = new SysOrganization();
            sysOrganization.setOrgCode(t.getMkCode());
            sysOrganization.setOrgName(t.getMkFullName());
            return sysOrganization;
        }).collect(Collectors.toList());
        return collect;

    }
    /**
     *   获取华能所有子煤矿
     * @return
     */
    @Override
    public List<SysOrganization> selectCodeSubMineList(String companyCode,String mineCode) {
//        List<SysOrganization> list = new ArrayList<>();
//        SysOrganizationVo sysOrganizationVo = this.selectCodeSubList();
//        //二级
//        List<SysOrganizationVo> subCodeList = sysOrganizationVo.getSubCodeList();
//        for (SysOrganizationVo organizationVo : subCodeList) {
//            //三级
//            for (SysOrganizationVo vo : organizationVo.getSubCodeList()) {
//                SysOrganization sysOrganization = new SysOrganization();
//                sysOrganization.setOrgCode(vo.getOrgCode());
//                sysOrganization.setOrgName(vo.getOrgName());
//                list.add(sysOrganization);
//            }
//        }
        //获取dim模式里煤矿信息
        List<DimCoalMineBasicInfoPo> dimCoalMineBasicInfoPos = dimCoalMineBasicInfoMapper.selectList(new LambdaQueryWrapper<DimCoalMineBasicInfoPo>()
                .eq(StringUtils.isNotBlank(companyCode), DimCoalMineBasicInfoPo::getMqCode, companyCode)
                .eq(StringUtils.isNotBlank(mineCode), DimCoalMineBasicInfoPo::getMkCode, mineCode));

        // 过滤掉煤矿编码为空的记录
        dimCoalMineBasicInfoPos = dimCoalMineBasicInfoPos.stream()
                .filter(t -> t.getMkCode() != null && !t.getMkCode().isEmpty())
                .collect(Collectors.toList());

        //去掉马蹄沟（620824009852）和刘园子煤矿（621022009406）
        List<String> codesToRemove = Arrays.asList("620824009852", "621022009406");
        dimCoalMineBasicInfoPos = dimCoalMineBasicInfoPos.stream()
                .filter(t -> !codesToRemove.contains(t.getMkCode()))
                .collect(Collectors.toList());




        // 按照 mkRank 排序
        List<DimCoalMineBasicInfoPo> sortedList = dimCoalMineBasicInfoPos.stream()
                .sorted(Comparator.nullsLast(Comparator.comparing(DimCoalMineBasicInfoPo::getMkRank)))
                .collect(Collectors.toList());

        List<SysOrganization> collect = sortedList.stream().map(t -> {
            SysOrganization sysOrganization = new SysOrganization();
            sysOrganization.setOrgCode(t.getMkCode());
            sysOrganization.setOrgName(t.getMkFullName());
            return sysOrganization;
        }).collect(Collectors.toList());
        return collect;

    }

    /**
     * 获取华能所有子煤矿带所有信息
     * @return
     */
    @Override
    public List<DimCoalMineBasicInfoPo> selectCodeSubMineInfoList() {
        //获取dim模式里煤矿信息
        List<DimCoalMineBasicInfoPo> dimCoalMineBasicInfoPos = dimCoalMineBasicInfoMapper.selectList(null);

        // 过滤掉煤矿编码为空的记录
        dimCoalMineBasicInfoPos = dimCoalMineBasicInfoPos.stream()
                .filter(t -> t.getMkCode() != null && !t.getMkCode().isEmpty())
                .collect(Collectors.toList());

        //去掉马蹄沟（620824009852）和刘园子煤矿（621022009406）
        List<String> codesToRemove = Arrays.asList("620824009852", "621022009406");
        dimCoalMineBasicInfoPos = dimCoalMineBasicInfoPos.stream()
                .filter(t -> !codesToRemove.contains(t.getMkCode()))
                .collect(Collectors.toList());


        // 按照 mkRank 排序
        List<DimCoalMineBasicInfoPo> sortedList = dimCoalMineBasicInfoPos.stream()
                .sorted(Comparator.nullsLast(Comparator.comparing(DimCoalMineBasicInfoPo::getMkRank)))
                .collect(Collectors.toList());

        return sortedList;
    }
    @Override
    public List<DimCoalMineBasicInfoPo> selectCodeSubMineInfoList(String companyCode,String mineCode) {
        //获取dim模式里煤矿信息
        List<DimCoalMineBasicInfoPo> dimCoalMineBasicInfoPos = dimCoalMineBasicInfoMapper.selectList(new LambdaQueryWrapper<DimCoalMineBasicInfoPo>()
                .eq(StringUtils.isNotBlank(companyCode), DimCoalMineBasicInfoPo::getMqCode, companyCode)
                .eq(StringUtils.isNotBlank(mineCode), DimCoalMineBasicInfoPo::getMkCode, mineCode));

        // 过滤掉煤矿编码为空的记录
        dimCoalMineBasicInfoPos = dimCoalMineBasicInfoPos.stream()
                .filter(t -> t.getMkCode() != null && !t.getMkCode().isEmpty())
                .collect(Collectors.toList());

        //去掉马蹄沟（620824009852）和刘园子煤矿（621022009406）
        List<String> codesToRemove = Arrays.asList("620824009852", "621022009406");
        dimCoalMineBasicInfoPos = dimCoalMineBasicInfoPos.stream()
                .filter(t -> !codesToRemove.contains(t.getMkCode()))
                .collect(Collectors.toList());


        // 按照 mkRank 排序
        List<DimCoalMineBasicInfoPo> sortedList = dimCoalMineBasicInfoPos.stream()
                .sorted(Comparator.nullsLast(Comparator.comparing(DimCoalMineBasicInfoPo::getMkRank)))
                .collect(Collectors.toList());

        return sortedList;
    }

    @Override
    public List<DimCoalMineBasicInfoPo> selectCodeSubMineInfoAllList(String companyCode, String mineCode) {
        //获取dim模式里煤矿信息
        List<DimCoalMineBasicInfoPo> dimCoalMineBasicInfoPos = dimCoalMineBasicInfoMapper.selectList(new LambdaQueryWrapper<DimCoalMineBasicInfoPo>()
                .eq(StringUtils.isNotBlank(companyCode), DimCoalMineBasicInfoPo::getMqCode, companyCode)
                .eq(StringUtils.isNotBlank(mineCode), DimCoalMineBasicInfoPo::getMkCode, mineCode));

        // 过滤掉煤矿编码为空的记录
        dimCoalMineBasicInfoPos = dimCoalMineBasicInfoPos.stream()
                .filter(t -> t.getMkCode() != null && !t.getMkCode().isEmpty())
                .collect(Collectors.toList());

        //去掉马蹄沟（620824009852）和刘园子煤矿（621022009406）
//        List<String> codesToRemove = Arrays.asList("620824009852", "621022009406");
//        dimCoalMineBasicInfoPos = dimCoalMineBasicInfoPos.stream()
//                .filter(t -> !codesToRemove.contains(t.getMkCode()))
//                .collect(Collectors.toList());


        // 按照 mkRank 排序
        List<DimCoalMineBasicInfoPo> sortedList = dimCoalMineBasicInfoPos.stream()
                .sorted(Comparator.nullsLast(Comparator.comparing(DimCoalMineBasicInfoPo::getMkRank)))
                .collect(Collectors.toList());

        return sortedList;
    }

    @Override
    public List<OutLimitAlarmingInfoVO> alarmInfoList(String mineCode) {
        //获取所有煤矿的报警超限数据
        List<OutLimitAlarmingInfoVO> vo = new ArrayList<>();
        //获取所有煤矿
        List<SysOrganization> list = this.selectCodeSubMineList();

        //去除露天矿
        //魏家峁 150622B0012000210118
        // 铧尖  未知
        // 伊敏  150724B0012000510053
        List<String> codesToRemove = Arrays.asList("150622B0012000210118", "150724B0012000510053");
        list = list.stream()
                .filter(dto -> !codesToRemove.contains(dto.getOrgCode()))
                .collect(Collectors.toList());

        for (SysOrganization sysOrganization : list) {
            String orgCode = sysOrganization.getOrgCode();
           List<AqjcYcbjPo>  ycbjList =aqjcYcbjMapper.selectBJOverrunList(orgCode);
            if (ycbjList.isEmpty()) {
                continue;
            }
            List<OutLimitAlarmingInfoVO> collect = ycbjList.stream().map(t -> {
                OutLimitAlarmingInfoVO outLimitAlarmingInfoVO = new OutLimitAlarmingInfoVO();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                outLimitAlarmingInfoVO.setMineName(sysOrganization.getOrgName());
                outLimitAlarmingInfoVO.setMineCode(orgCode);
                outLimitAlarmingInfoVO.setPointCode(t.getCdbh());
                outLimitAlarmingInfoVO.setAlarmType(t.getYclx());
                outLimitAlarmingInfoVO.setAlarmTypeName("超限报警");
                outLimitAlarmingInfoVO.setPointLocation(t.getCdazwz());
                if (StringUtils.isNotBlank(t.getYckssj())) {
                    try {
                        outLimitAlarmingInfoVO.setAlarmBeginTime(simpleDateFormat.parse(t.getYckssj()));
                    } catch (ParseException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    outLimitAlarmingInfoVO.setAlarmBeginTime(null);
                }
                if (StringUtils.isNotBlank(t.getYcjssj())) {
                    try {
                        outLimitAlarmingInfoVO.setAlarmEndTime(simpleDateFormat.parse(t.getYcjssj()));
                    } catch (ParseException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    outLimitAlarmingInfoVO.setAlarmEndTime(null);
                }
                if (StringUtils.isNotBlank(t.getYckssj()) && StringUtils.isNotBlank(t.getYcjssj())) {
                    //报警时长
                    try {
                        String duration = getDuration(simpleDateFormat.parse(t.getYckssj()), simpleDateFormat.parse(t.getYcjssj()));
                        outLimitAlarmingInfoVO.setAlarmDuration(duration);
                    } catch (ParseException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    outLimitAlarmingInfoVO.setAlarmDuration("");
                }
                if (StringUtils.isNotBlank(t.getYcqjzdz())) {
                    outLimitAlarmingInfoVO.setAlarmMaxValue(new BigDecimal(t.getYcqjzdz()));
                } else {
                    outLimitAlarmingInfoVO.setAlarmMaxValue(null);
                }

                outLimitAlarmingInfoVO.setAlarmCause(t.getYcyy());
                outLimitAlarmingInfoVO.setMeasure(t.getClcs());
                outLimitAlarmingInfoVO.setStatus(StringUtils.isNotBlank(t.getClcs()) ? "完成" : "未完成");
                return outLimitAlarmingInfoVO;
            }).collect(Collectors.toList());
            collect.forEach(volist -> vo.add(volist));
        }
        return vo;
    }
    /**
     * 获取煤业公司井工矿煤矿列表
     * @return
     */
    @Override
    public List<SysOrganization> selectCodeUndergroundMiningSubMineList() {
        List<DimCoalMineBasicInfoPo> undergroundMiningList = dimCoalMineBasicInfoMapper.selectList(new LambdaQueryWrapper<DimCoalMineBasicInfoPo>()
                .eq(DimCoalMineBasicInfoPo::getMiningMethodTypes, "井工矿"));



        // 过滤掉煤矿编码为空的记录
        undergroundMiningList = undergroundMiningList.stream()
                .filter(t -> t.getMkCode() != null && !t.getMkCode().isEmpty())
                .collect(Collectors.toList());


        //去掉马蹄沟（620824009852）和刘园子煤矿（621022009406）
        List<String> codesToRemove = Arrays.asList("620824009852", "621022009406");
        undergroundMiningList = undergroundMiningList.stream()
                .filter(t -> !codesToRemove.contains(t.getMkCode()))
                .collect(Collectors.toList());

        // 按照 mkRank 排序
        List<DimCoalMineBasicInfoPo> sortedList = undergroundMiningList.stream()
                .sorted(Comparator.nullsLast(Comparator.comparing(DimCoalMineBasicInfoPo::getMkRank)))
                .collect(Collectors.toList());





        List<SysOrganization> collect = sortedList.stream().map(t -> {
            SysOrganization sysOrganization = new SysOrganization();
            sysOrganization.setOrgCode(t.getMkCode());
            sysOrganization.setOrgName(t.getMkFullName());
            return sysOrganization;
        }).collect(Collectors.toList());

        return collect;
    }
    /**
     * 获取煤业公司井工矿煤矿列表
     * @return
     */
    @Override
    public List<SysOrganization> selectCodeUndergroundMiningSubMineList(String companyCode,String mineCode) {
        List<DimCoalMineBasicInfoPo> undergroundMiningList = dimCoalMineBasicInfoMapper.selectList(new LambdaQueryWrapper<DimCoalMineBasicInfoPo>()
                .eq(DimCoalMineBasicInfoPo::getMiningMethodTypes, "井工矿")
                .eq(StringUtils.isNotBlank(companyCode), DimCoalMineBasicInfoPo::getMqCode, companyCode)
                .eq(StringUtils.isNotBlank(mineCode), DimCoalMineBasicInfoPo::getMkCode, mineCode));



        // 过滤掉煤矿编码为空的记录
        undergroundMiningList = undergroundMiningList.stream()
                .filter(t -> t.getMkCode() != null && !t.getMkCode().isEmpty())
                .collect(Collectors.toList());


        //去掉马蹄沟（620824009852）和刘园子煤矿（621022009406）
        List<String> codesToRemove = Arrays.asList("620824009852", "621022009406");
        undergroundMiningList = undergroundMiningList.stream()
                .filter(t -> !codesToRemove.contains(t.getMkCode()))
                .collect(Collectors.toList());

        // 按照 mkRank 排序
        List<DimCoalMineBasicInfoPo> sortedList = undergroundMiningList.stream()
                .sorted(Comparator.nullsLast(Comparator.comparing(DimCoalMineBasicInfoPo::getMkRank)))
                .collect(Collectors.toList());





        List<SysOrganization> collect = sortedList.stream().map(t -> {
            SysOrganization sysOrganization = new SysOrganization();
            sysOrganization.setOrgCode(t.getMkCode());
            sysOrganization.setOrgName(t.getMkFullName());
            return sysOrganization;
        }).collect(Collectors.toList());

        return collect;
    }

    @Override
    public List<DimCoalMineBasicInfoPo> selectCodeUndergSubMineInfoList() {
        //获取dim模式里煤矿信息
        List<DimCoalMineBasicInfoPo> dimCoalMineBasicInfoPos = dimCoalMineBasicInfoMapper.selectList(new LambdaQueryWrapper<DimCoalMineBasicInfoPo>()
                .eq(DimCoalMineBasicInfoPo::getMiningMethodTypes, "井工矿"));

        // 过滤掉煤矿编码为空的记录
        dimCoalMineBasicInfoPos = dimCoalMineBasicInfoPos.stream()
                .filter(t -> t.getMkCode() != null && !t.getMkCode().isEmpty())
                .collect(Collectors.toList());

        //去掉马蹄沟（620824009852）和刘园子煤矿（621022009406）
        List<String> codesToRemove = Arrays.asList("620824009852", "621022009406");
        dimCoalMineBasicInfoPos = dimCoalMineBasicInfoPos.stream()
                .filter(t -> !codesToRemove.contains(t.getMkCode()))
                .collect(Collectors.toList());


        // 按照 mkRank 排序
        List<DimCoalMineBasicInfoPo> sortedList = dimCoalMineBasicInfoPos.stream()
                .sorted(Comparator.nullsLast(Comparator.comparing(DimCoalMineBasicInfoPo::getMkRank)))
                .collect(Collectors.toList());

        return sortedList;
    }
    @Override
    public List<DimCoalMineBasicInfoPo> selectCodeUndergSubMineInfoList(String companyCode,String mineCode) {
        //获取dim模式里煤矿信息
        List<DimCoalMineBasicInfoPo> dimCoalMineBasicInfoPos = dimCoalMineBasicInfoMapper.selectList(new LambdaQueryWrapper<DimCoalMineBasicInfoPo>()
                .eq(DimCoalMineBasicInfoPo::getMiningMethodTypes, "井工矿")
                .eq(StringUtils.isNotEmpty(mineCode), DimCoalMineBasicInfoPo::getMkCode, mineCode)
                .eq(StringUtils.isNotEmpty(companyCode), DimCoalMineBasicInfoPo::getMqCode, companyCode));


        // 过滤掉煤矿编码为空的记录
        dimCoalMineBasicInfoPos = dimCoalMineBasicInfoPos.stream()
                .filter(t -> t.getMkCode() != null && !t.getMkCode().isEmpty())
                .collect(Collectors.toList());

        //去掉马蹄沟（620824009852）和刘园子煤矿（621022009406）
        List<String> codesToRemove = Arrays.asList("620824009852", "621022009406");
        dimCoalMineBasicInfoPos = dimCoalMineBasicInfoPos.stream()
                .filter(t -> !codesToRemove.contains(t.getMkCode()))
                .collect(Collectors.toList());


        // 按照 mkRank 排序
        List<DimCoalMineBasicInfoPo> sortedList = dimCoalMineBasicInfoPos.stream()
                .sorted(Comparator.nullsLast(Comparator.comparing(DimCoalMineBasicInfoPo::getMkRank)))
                .collect(Collectors.toList());

        return sortedList;
    }

    /**
     * 获取煤业公司露天矿煤矿列表
     * @return
     */
    @Override
    public List<SysOrganization> selectCodeOutdoorsSubMineList() {
        List<DimCoalMineBasicInfoPo> outdoorsSubList = dimCoalMineBasicInfoMapper.selectList(new LambdaQueryWrapper<DimCoalMineBasicInfoPo>()
                .eq(DimCoalMineBasicInfoPo::getMiningMethodTypes, "露天矿"));

        // 过滤掉煤矿编码为空的记录
        outdoorsSubList = outdoorsSubList.stream()
                .filter(t -> t.getMkCode() != null && !t.getMkCode().isEmpty())
                .collect(Collectors.toList());

        // 按照 mkRank 排序
        List<DimCoalMineBasicInfoPo> sortedList = outdoorsSubList.stream()
                .sorted(Comparator.nullsLast(Comparator.comparing(DimCoalMineBasicInfoPo::getMkRank)))
                .collect(Collectors.toList());

        List<SysOrganization> collect = sortedList.stream().map(t -> {
            SysOrganization sysOrganization = new SysOrganization();
            sysOrganization.setOrgCode(t.getMkCode());
            sysOrganization.setOrgName(t.getMkFullName());
            return sysOrganization;
        }).collect(Collectors.toList());

        return collect;
    }

    @Override
    public List<SysOrganization> getMineCodeListByCompanyCode(String companyCode) {
        //根据公司编码获取公司名称
        List<DimCoalMineBasicInfoPo> dimCoalMineBasicInfoPos = dimCoalMineBasicInfoMapper.selectList(
                new LambdaQueryWrapper<DimCoalMineBasicInfoPo>()
                        .eq(StringUtils.isNotBlank(companyCode), DimCoalMineBasicInfoPo::getMqCode, companyCode));
        if (dimCoalMineBasicInfoPos.isEmpty()) {
            return new ArrayList<>();
        }
        //排除煤矿编码为空或者null的数据
        dimCoalMineBasicInfoPos = dimCoalMineBasicInfoPos.stream().filter(t -> t.getMkCode() != null && !t.getMkCode().isEmpty()).collect(Collectors.toList());



        //排序
        dimCoalMineBasicInfoPos = dimCoalMineBasicInfoPos.stream()
                .sorted(Comparator.nullsLast(Comparator.comparing(DimCoalMineBasicInfoPo::getMkRank)))
                .collect(Collectors.toList());


        List<SysOrganization> collect = dimCoalMineBasicInfoPos.stream().map(t -> {
            SysOrganization sysOrganization = new SysOrganization();
            sysOrganization.setOrgCode(t.getMkCode());
            sysOrganization.setOrgName(t.getMkFullName());
            return sysOrganization;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 获取所有公司列表
     * @return
     */
    @Override
    public List<SysOrganization> getAllCompanyMineCodeList() {
        // 获取所有煤矿
        List<DimCoalMineBasicInfoPo> dimCoalMineBasicInfoPos = dimCoalMineBasicInfoMapper.selectList(null);

        // 检查是否为空
        if (dimCoalMineBasicInfoPos == null || dimCoalMineBasicInfoPos.isEmpty()) {
            return new ArrayList<>();
        }

        // 分组并取每组第一个，排除空组
        List<DimCoalMineBasicInfoPo> firstInGroups = dimCoalMineBasicInfoPos.stream()
                .collect(Collectors.groupingBy(DimCoalMineBasicInfoPo::getMqShortName))
                .values().stream()
                .filter(list -> !list.isEmpty()) // 排除空组
                .map(list -> list.get(0)) // 获取每组第一个元素
                .collect(Collectors.toList());

        // 排序
        firstInGroups.sort(Comparator.comparing(DimCoalMineBasicInfoPo::getMqRank, Comparator.nullsLast(Comparator.naturalOrder())));
        // 转换为 SysOrganization 列表并返回
        return firstInGroups.stream()
                .map(t -> {
                    SysOrganization sysOrganization = new SysOrganization();
                    sysOrganization.setOrgCode(t.getMqCode());
                    sysOrganization.setOrgName(t.getMqShortName());
                    return sysOrganization;
                })
                .collect(Collectors.toList());
    }

    /**
     * pc-大屏首页-超限统计
     * @param type
     * @return
     */
    @Override
    public TransfiniteStatisticsVo getTransfiniteStatistics(String companyCode,String mineCode,String type) {
        //获取煤矿
        List<SysOrganization> sysOrganizations = this.selectCodeSubMineList(companyCode, mineCode);
        List<String> stringList = sysOrganizations.stream().map(t -> {
            return t.getOrgCode();
        }).collect(Collectors.toList());

        TransfiniteStatisticsVo vo = new TransfiniteStatisticsVo();
        List<Integer> cH4WarnCountList = new ArrayList<>();
        List<Integer>  coWarnCountList = new ArrayList<>();
        List<LocalDate> dateList = new ArrayList<>();
        //获取今天的日期
        Date now = new Date();
        //获取开始日期
        Date startDate = null;
        if ("周".equals(type)) {
            //默认七天
            startDate = DateUtils.addDays(now, -7);
        } else if ("月".equals(type)) {
            startDate = DateUtils.addMonths(now, -1);
        } else {
            startDate = DateUtils.addDays(now, -10);
        }
        // 转换 Date 到 LocalDate
        LocalDate startLocalDate = startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDate nowLocalDate = now.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        //判断开始时间到现在有多少天
        // 计算天数
        long days = ChronoUnit.DAYS.between(startLocalDate, nowLocalDate);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < days; i++) {
            Date date = DateUtils.addDays(startDate, i);
            String format = dateFormat.format(date);
            dateList.add(date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
            //获取当天的所有数据
            List<DwsAqjcYcbjDFPo> mineDwsAqjkCdbjListByDate = dwsService.getMineDwsAqjkCdbjListByDate(stringList,date);

            if (!mineDwsAqjkCdbjListByDate.isEmpty()) {
                coWarnCountList.add(0);
                cH4WarnCountList.add(0);
            } else {
                // 对字段求和
                //最大领导
                int coAlarm = mineDwsAqjkCdbjListByDate.stream()
                        .mapToInt(po -> po.getCoCnt() != null ? po.getCoCnt() : 0)
                        .sum();
                //最大人员
                int ch4Alarm = mineDwsAqjkCdbjListByDate.stream()
                        .mapToInt(po -> po.getCh4Cnt() != null ? po.getCh4Cnt() : 0)
                        .sum();


                coWarnCountList.add(coAlarm);
                cH4WarnCountList.add(ch4Alarm);
            }


        }
        vo.setDate(dateList);
        vo.setCoWarnCount(coWarnCountList);
        vo.setCH4WarnCount(cH4WarnCountList);
        return vo;
    }

    @Override
    public List<SysOrganizationVo> selectGroupCodeSubList() {
        //查询dim 所有数据
        List<DimCoalMineBasicInfoPo> dimCoalMineBasicInfoPos = dimCoalMineBasicInfoMapper.selectList(null);
        //分组  一级公司
        Map<String, List<DimCoalMineBasicInfoPo>> listMap1= dimCoalMineBasicInfoPos.stream()
                .filter(t -> t.getMyCode() != null)
                .collect(Collectors.groupingBy(DimCoalMineBasicInfoPo::getMyCode));
        List<SysOrganizationVo> voList1 = new ArrayList<>();
        listMap1.forEach((key, value) -> {
            SysOrganizationVo sysOrganizationVo = new SysOrganizationVo();
            DimCoalMineBasicInfoPo dimCoalMineBasicInfoPo = value.get(0);
            sysOrganizationVo.setOrgName(dimCoalMineBasicInfoPo.getMyFullName());
            sysOrganizationVo.setOrgCode(key);
            sysOrganizationVo.setParentCode("");
            //根据煤业按照煤企分组
            Map<String, List<DimCoalMineBasicInfoPo>> listMap2 = value.stream().filter(t -> t.getMqCode() != null).collect(Collectors.groupingBy(DimCoalMineBasicInfoPo::getMqCode));
            List<SysOrganizationVo> voList2 = new ArrayList<>();
            listMap2.forEach((key2, value2) -> {
                SysOrganizationVo vo2 = new SysOrganizationVo();
                //煤企数据
                vo2.setOrgCode(key2);
                vo2.setOrgName(value2.get(0).getMqFullName());
                vo2.setParentCode(key);
                //煤矿分组
                Map<String, List<DimCoalMineBasicInfoPo>> listMap3 = value2.stream().filter(t -> t.getMkCode() != null).collect(Collectors.groupingBy(DimCoalMineBasicInfoPo::getMkCode));
                List<SysOrganizationVo> voList3 = new ArrayList<>();
                listMap3.forEach((key3, value3) -> {
                    SysOrganizationVo vo3 = new SysOrganizationVo();
                    vo3.setOrgCode(key3);
                    vo3.setOrgName(value3.get(0).getMkFullName());
                    vo3.setParentCode(key2);
                    voList3.add(vo3);
                });
                vo2.setSubCodeList(voList3);
                voList2.add(vo2);
            });
            sysOrganizationVo.setSubCodeList(voList2);
            voList1.add(sysOrganizationVo);
        });

        return voList1;
    }


    private String getDuration(Date startTime, Date endTime) {
        LocalDateTime startDateTime = LocalDateTime.ofInstant(startTime.toInstant(), java.time.ZoneId.systemDefault());
        LocalDateTime endDateTime = LocalDateTime.ofInstant(endTime.toInstant(), java.time.ZoneId.systemDefault());
        Duration duration = Duration.between(startDateTime, endDateTime);
        long minutes = duration.toMinutes(); // 获取分钟数
        long seconds = duration.minusMinutes(minutes).getSeconds(); // 获取剩余的秒数
        String timeString = "";
        if (duration.toHours() < 1) {
            timeString = minutes + "分钟" + seconds + "秒";
        } else {
            timeString = duration.toHours() + "小时" + minutes + "分钟" + seconds + "秒";
        }
        return timeString;
    }
}
